package com.yangye.springclouddemozuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.FilterType;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by yangye on 2019/6/26
 */
public class AuthFilter extends ZuulFilter {
	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String authorization = request.getHeader("Authorization");
		if (!StringUtils.equals("admin", authorization)) {
			ctx.setSendZuulResponse(true);
			ctx.setResponseStatusCode(401);
			ctx.getResponse().setContentType("text/html;charset=UTF-8");
			ctx.setResponseBody("认证失败");
			return null;
		}
		return null;
	}
}
